package com.fingard.text;

public class UrlHelper {

    public static String[] pickupIpAndPort(String p_url) {
        String[] retVal = new String[2];
        retVal[0] = "";
        retVal[1] = "";
        String urlOri = p_url.trim().toLowerCase();
        String url = urlOri;
        int idx = url.indexOf("/");
        if (idx >= 0) {
            url = url.substring(idx);
        }
        url = StringHelper.trimStart(url, "/");

        idx = url.indexOf("/");
        if (idx >= 0) {
            url = url.substring(0, idx);
        }
        int idx2 = url.indexOf(":");
        if (idx2 > 0) {
            retVal[0] = url.substring(0, idx2);
            retVal[1] = url.substring(idx2 + 1);
        } else if (urlOri.startsWith("https")) {
        	retVal[0] = url;
            retVal[1] = "443";
        } else if (urlOri.startsWith("http")) {
        	retVal[0] = url;
            retVal[1] = "80";
        } 
        return retVal;
    }
    
    /**取扩展名*/
    public static String getExt(String p_url){
    	if(StringHelper.hasAnyChar(p_url)){
    		int idx1 = p_url.indexOf("?");
    		String page = "";
    		if(idx1>=0){
    			page = p_url.substring(0, idx1);
    		}else{
    			page = p_url;
    		}
    		int idx2 = page.lastIndexOf(".");
    		if(idx2>=0){
    			return page.substring(idx2+1);
    		}
    	}
    	return "";
    }

    /**
     * 获取当前地址中的域名并和目标域名进行替换
     *
     * @param serverUrl
     * @param domain
     * @return
     */
    public static String replaceUrlDomain(String serverUrl, String domain) {
        String srvUrl = serverUrl.replace("http://", "").replace("https://", "");
        srvUrl = StringHelper.trimStart(srvUrl, "/");
        int indx = srvUrl.indexOf("/");
        if (indx > 0) {
            srvUrl = srvUrl.substring(0, indx);
        }
        return serverUrl.replace(srvUrl, domain);
    }

    /**
     * 获取当前地址中的域名
     *
     * @param serverUrl
     * @param domain
     * @return
     */
    public static String getUrlDomain(String serverUrl, String domain) {
        String srvUrl = serverUrl.replace("http://", "").replace("https://", "");
        srvUrl = StringHelper.trimStart(srvUrl, "/");
        int indx = srvUrl.indexOf("/");
        if (indx > 0) {
            srvUrl = srvUrl.substring(0, indx);
        }
        return srvUrl;
    }
    
    /**http://127.0.0.1:6001/dsp，提取/dsp*/
    public static String getPage(String pUrl){
    	int idx = pUrl.indexOf("//");
    	if(idx > 0){
    		int idx2 = pUrl.indexOf("/", idx+2);
    		if(idx2>0){
    			return pUrl.substring(idx2);
    		}
    	}
    	return "/";
    }
}
